package com.doit.day01;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.RandomUtils;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.record.TimestampType;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.time.Duration;
import java.util.Arrays;
import java.util.HashMap;

public class KafkaConsumerDemo2 {
    public static void main(String[] args) throws InterruptedException, SQLException {
        //是否需要我们设置一些配置参数呢？
        HashMap<String, Object> map = new HashMap<>();
        map.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        map.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        map.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, MyConfig.HOST_AND_PORT);
        map.put(ConsumerConfig.GROUP_ID_CONFIG, "g006");
        //允许自动创建topic
        map.put("allow.auto.create.topics", "true");
        map.put("auto.offset.reset", "earliest");
        //是否自动提交偏移量 true代表的是回头将消费到哪的偏移量记录在__consumer_offsets 如果是false 就不记录
        map.put("enable.auto.commit", "false");//consumer_offsets
        //自动提交偏移量的间隔时间
//        map.put("auto.commit.interval.ms", "100000");
        //创建一个消费者的对象
        KafkaConsumer<String, String> consumer = new KafkaConsumer<>(map);
        //我读取哪个topic的数据
        //订阅主题
        consumer.subscribe(Arrays.asList("test3"));

        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456");
        PreparedStatement pps = conn.prepareStatement("insert into user_info values(?,?,?,?)");

        while (true) {
            //读取数据 ==》 业务逻辑的处理
            ConsumerRecords<String, String> poll = consumer.poll(Duration.ofMillis(Long.MAX_VALUE));
            //手动提交偏移量
            for (ConsumerRecord<String, String> consumerRecord : poll) {
                String value = consumerRecord.value();
                //往mysql里面写数据
                UserInfo userInfo = JSON.parseObject(value, UserInfo.class);
                //给？设置值
                //给?赋值
                pps.setInt(1,userInfo.getId());
                pps.setString(2,userInfo.getName());
                pps.setInt(3,userInfo.getAge());
                pps.setString(4,userInfo.getGender());
                pps.execute();
            }
        }
    }
}
